package com.hongkang.springtrains.web.config;

import com.hongkang.springtrains.service.UserService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.remoting.httpinvoker.HttpInvokerServiceExporter;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;
import org.springframework.web.servlet.handler.SimpleUrlHandlerMapping;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

import java.util.Properties;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.hongkang.springtrains.web"})
public class WebConfig extends WebMvcConfigurationSupport{

    /**
     * 创建JPS解析器
     * @return
     */
    @Override
    @Bean
    public ViewResolver mvcViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setExposeContextBeansAsAttributes(true);
        return resolver;
    }


    /**
     * 请用默认静态资源管理器处理静态资源，而非servlet
     * @param configurer
     */
    @Override
    protected void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }


    /**
     * 将Bean导出为基于http invoker 的RMI服务。
     * 设置代理类及服务接口
     * httpInvokerServiceExporter 实际为Controller
     * @param service
     * @return
     */
    @Bean
    public HttpInvokerServiceExporter userServiceExporter(UserService service){
        HttpInvokerServiceExporter exporter = new HttpInvokerServiceExporter();
        exporter.setService(service);
        exporter.setServiceInterface(UserService.class);
        return  exporter;
    }


    /**
     * 设置映射关系
     * @return
     */
    @Bean
    public HandlerMapping httpInvokerMapping(){
        SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
        Properties properties = new Properties();
        properties.setProperty("/user.service","userServiceExporter");
        mapping.setMappings(properties);
        return  mapping;
    }
}
